package com.xxl.job.admin.core.scheduler;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.thread.*;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.client.ExecutorBizClient;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author xuxueli 2018-10-28 00:18:17
 */

public class XxlJobScheduler  {
    private static final Logger logger = LoggerFactory.getLogger(XxlJobScheduler.class);


    public void init() throws Exception {
        // init i18n
        initI18n();

        // admin trigger pool start
        // 启动快慢线程池
        //fastTriggerPool
        //slowTriggerPool
        JobTriggerPoolHelper.toStart();

        // admin registry monitor run
        //启动registryOrRemoveThreadPool和registryMonitorThread
        //registryMonitorThread更新注册执行器信息，按照心跳间隔循环执行，
        JobRegistryHelper.getInstance().start();

        // admin fail-monitor run
        //任务失败重启线程，轮询日志列表，发现有失败的则按照失败重试策略重启和预警,间隔10ms循环执行
        JobFailMonitorHelper.getInstance().start();

        // admin lose-monitor run ( depend on JobTriggerPoolHelper )
        //启动回调线程池callbackThreadPool
        //启动monitorThread线程，监测丢失的任务
        //任务结果丢失处理：调度记录停留在 "运行中" 状态超过10min，且对应执行器心跳注册失败不在线，则将本地调度主动标记失败；
        JobCompleteHelper.getInstance().start();

        // admin log report
        //启动logrThread线程
        //每天生成日报，每次生成前三天的日报
        //定时删除日志（每天执行一次）
        //删除周期与logretentiondays配置相关，默认为30天
        JobLogReportHelper.getInstance().start();

        // start-schedule  ( depend on JobTriggerPoolHelper )
        //使用了xxl_job_lock表的锁来保证原子性
        //使用了时间轮，xxl-job 为了避免处理耗时太长，会跨过刻度，多向前校验一个刻度；也就是当指针指到 2s 时，会把 1s 和 2s 位置的任务同时读取出来。
        //scheduleThread，读取当前快慢线程池最大容量之和的数据。条件为下次执行时间在当前时间+5秒之前的所有任务
        //如果任务本该在当前时间-5秒前执行，则按照misfire策略进行执行（不执行或执行一次）
        //如果任务本该在当前时间之前执行，则马上执行
        //如果任务应该在当前时间+5s内执行，则放入时间轮
        JobScheduleHelper.getInstance().start();

        logger.info(">>>>>>>>> init xxl-job admin success.");
    }

    
    public void destroy() throws Exception {

        // stop-schedule
        JobScheduleHelper.getInstance().toStop();

        // admin log report stop
        JobLogReportHelper.getInstance().toStop();

        // admin lose-monitor stop
        JobCompleteHelper.getInstance().toStop();

        // admin fail-monitor stop
        JobFailMonitorHelper.getInstance().toStop();

        // admin registry stop
        JobRegistryHelper.getInstance().toStop();

        // admin trigger pool stop
        JobTriggerPoolHelper.toStop();

    }

    // ---------------------- I18n ----------------------

    private void initI18n(){
        for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
            item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
        }
    }

    // ---------------------- executor-client ----------------------
    private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
    public static ExecutorBiz getExecutorBiz(String address) throws Exception {
        // valid
        if (address==null || address.trim().length()==0) {
            return null;
        }

        // load-cache
        address = address.trim();
        ExecutorBiz executorBiz = executorBizRepository.get(address);
        if (executorBiz != null) {
            return executorBiz;
        }

        // set-cache
        executorBiz = new ExecutorBizClient(address, XxlJobAdminConfig.getAdminConfig().getAccessToken());

        executorBizRepository.put(address, executorBiz);
        return executorBiz;
    }

}
